package redis.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class RedisClient {

    private static Socket socket;
    private static OutputStream write;
    private static InputStream read;

    public static void main(String[] args) throws IOException {
        socket = new Socket("127.0.0.1", 6379);
        write = socket.getOutputStream();
        read = socket.getInputStream();

        Scanner scanner = new Scanner(System.in);

        // 判断是否还有输入
        while (scanner.hasNextLine()) {
            String str = scanner.nextLine();

            // 构造协议
            String command = buildCommand(str);

            System.out.println("发送命令为： \r\n" + command);

            String result = sendCommand(command);

            System.out.println("响应命令为：" + result);
        }
    }

    /**
     * 构造指令
     */
    public static String buildCommand(String command) {
        if (command != null && !"".equals(command)) {
            String[] strs = command.split(",");

            StringBuilder builder = new StringBuilder();
            builder.append("*").append(strs.length).append("\r\n");
            for (String str : strs) {
                builder.append("$").append(str.length()).append("\r\n");
                builder.append(str).append("\r\n");
            }
            return builder.toString();
        }
        return null;
    }

    /**
     * 发送指令
     *
     * @param commannd
     * @return
     * @throws IOException
     */
    private static String sendCommand(String commannd) throws IOException {
        write.write(commannd.toString().getBytes());
        byte[] bytes = new byte[1024];
        read.read(bytes);

        return new String(bytes, "UTF-8");
    }
}
